local modname = "wechat_jssdk_config"
local _M = { _VERSION = '0.0.1' }
_G[modname] = _M

local cjson = require("cjson")

local table_insert = table.insert
local table_sort = table.sort
local table_concat = table.concat
local ngx_req = ngx.req
local ngx_log = ngx.log
local ngx_print = ngx.print
local ngx_exit = ngx.exit

local function _verify_request_params(params)
  if params.method ~= "GET" then
    return nil, "register not support " .. params.method .. " method"
  end
  if not params.key then
    return nil, "missing key"
  end
  return true
end

local mt = {
  __call = function(_)
    -- request arguments
    local args = ngx_req.get_uri_args()

    local params = {
      method = ngx_req.get_method(),
      key = args.key,
    }

    local ok, err = _verify_request_params(params)

    ngx.header["Content-Type"] = "application/json"

    local red = require("resty.wechat.utils.redis"):connect(wechat_config.redis).redis

    local key_exist = red:sismember("app_set", params.key)

    if key_exist and key_exist == 0 then
      ngx_print(cjson.encode({ errmsg = "app_key:[" .. params.key .. "] is not registered!" }))
      return ngx_exit(ngx.HTTP_OK)
    end

    red:srem("app_set", params.key)
    red:del("app_data:" .. params.key)

    ngx_print(cjson.encode({ errmsg = "sucess deregister app : " .. params.key }))
    return ngx_exit(ngx.HTTP_OK)
  end,
}

return setmetatable(_M, mt)
